﻿// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using IdentityServerHost.Quickstart.UI;
using System.Reflection;
using Microsoft.AspNetCore.Identity;
using System;
using System.Linq;
using Chen.IdentityServer4.DbAll;
using Chen.IdentityServer4.Services;
using Chen.IdentityServer4.Extent;
using IdentityServer4.Services;

namespace Chen.IdentityServer4
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var rightConnectionString = Configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext<RightDbContext>(option => option.UseMySql(rightConnectionString));
            services.AddTransient<AccountService>();

            //services.AddDbContext<ApplicationDbContext>(option => option.UseMySql(connectionString));
            //services.AddIdentity<IdentityUser<int>, IdentityRole<int>>()
            //    .AddEntityFrameworkStores<ApplicationDbContext>()
            //    .AddDefaultTokenProviders();

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
            })
                //.AddAspNetIdentity<IdentityUser<int>>()
                //.AddTestUsers(TestUsers.Users)
                // this adds the config data from DB (clients, resources, CORS)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = b => b.UseMySql(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
                })
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = b => b.UseMySql(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
                });
            services.AddScoped<IProfileService, ProfileService>();
            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();
            //拓展
            builder.AddExtensionGrantValidator<SmsGrantValidator>();


            services.AddAuthentication()
                 .AddOpenIdConnect("Midea", "Midea", options =>
                 {
                     options.Authority = "http://localhost:5011";
                     options.ClientId = "123";
                     options.RequireHttpsMetadata = false;

                 })
                .AddGoogle(options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                    // register your IdentityServer with Google at https://console.developers.google.com
                    // enable the Google+ API
                    // set the redirect URI to https://localhost:5001/signin-google
                    options.ClientId = "copy client ID from Google here";
                    options.ClientSecret = "copy client secret from Google here";
                });


            ConfigureCors(services, Configuration);
        }

        private void ConfigureCors(IServiceCollection context, IConfiguration configuration)
        {
            context.AddCors(options =>
            {
                options.AddPolicy("AllowAnyOrigin",
                    builder => builder.AllowAnyOrigin()
                      .AllowAnyMethod()
                      .AllowAnyHeader());

                //options.AddDefaultPolicy(builder =>
                //{
                //    var corslist = configuration["App:CorsOrigins"]?
                //            .Split(",", StringSplitOptions.RemoveEmptyEntries)
                //            //.Select(o => o.RemovePostFix("/"))
                //            .ToArray() ?? Array.Empty<string>();
                //    builder
                //        .WithOrigins(corslist)
                //        .SetIsOriginAllowedToAllowWildcardSubdomains()
                //        .AllowAnyHeader()
                //        .AllowAnyMethod()
                //        .AllowCredentials();
                //});
            });
        }

        public void Configure(IApplicationBuilder app)
        {
            //if (Environment.IsDevelopment())
            //{
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            //}

            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseCors("AllowAnyOrigin");
            //SeedData.EnsureSeedData(Configuration.GetConnectionString("DefaultConnection"));
            //SeedData.EnsureEmployeeDataAll(app);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                //endpoints.MapDefaultControllerRoute();
            });
        }
    }
}
